<template>
  <div id="myDiv">
    <div>
      <input type="text" v-model="value">
      <button @click="handleSearch(value)">Search</button>
    </div>
    <div v-for="item in list" :key="item.tid" style="margin-bottom: 6px;">
      <div style="font-size: 16px;">{{item.title}} <span>{{item.name}}</span></div>
      <div>{{item.text}}</div>
    </div>
    <div style="font-size: 16px;">{{list.length}}</div>
  </div>
</template>

<script lang="ts">
import { ref } from 'vue'
// 防抖
const debounce = (fn:any, time:number) => {
  // eslint-disable-next-line @typescript-eslint/no-this-alias
  const that = this
  return function (args:any) {
    clearTimeout(fn.tid)
    fn.tid = setTimeout(() => {
      fn.call(that, args)
    }, time)
  }
}
export default {
  name: 'demoChild',
  setup () {
    // 初始化数据
    const value = ref('')
    const orginList:any = []
    let curPage = 1
    const pageSize = 30
    let prevY = 0
    const list = ref([])

    // 生成指定个数的随机字符串
    const genrateRandomWords = (n:number) => {
      const words = 'abcdefghijklmnopqrstuvwxyz你是好的嗯气短前端后端设计产品网但考虑到付款啦分手快乐的分类开发商的李开复封疆大吏师德师风吉林省附近'
      const len = words.length
      let ret = ''
      for (let i = 0; i < n; i++) {
        ret += words[Math.floor(Math.random() * len)]
      }
      return ret
    }
    // 生成10万条数据的list
    for (let i = 0; i < 100000; i++) {
      orginList.push({
        name: `xu_0${i}`,
        title: genrateRandomWords(12),
        text: `我是第${i}项目, 赶快 吧~~`,
        tid: `xx_${i}`
      })
    }

    // 设置数据
    const setList = (arr:any) => {
      list.value = arr
    }
    // 原始数据变成列表
    list.value = orginList.slice(0, pageSize * curPage)
    const scrollAndLoading = () => {
      const poll:any = document.getElementById('myDiv')
      if (window.scrollY > prevY) { // 判断用户是否向下滚动
        prevY = window.scrollY
        console.log(poll, window.innerHeight)
        if (poll.getBoundingClientRect().top <= window.innerHeight) {
          curPage++
          setList(orginList.slice(0, pageSize * curPage))
        }
      }
    }
    const myScroll = () => {
      // something code
      const getData = debounce(scrollAndLoading, 300)
      window.addEventListener('scroll', getData, false)
      return () => {
        window.removeEventListener('scroll', getData, false)
      }
    }
    // 运行滚动事件
    myScroll()

    // 搜索功能
    const handleSearch = (v:string) => {
      list.value = orginList.filter((item:any) => {
        return item.title.indexOf(v) > -1
      })
    }

    return {
      list,
      value,
      handleSearch,
      setList
    }
  }
}
</script>

<style>
</style>
